# -*- coding: utf-8 -*-
import os, time, sys
from make_and_upload_report.uploadfile import UploadFileByHttp
import cgi

html1 = """<html>
<style type="text/css">
body {
    font:normal 68% verdana,arial,helvetica;
    color:#000000;
}
table tr td, table tr th {
    font-size: 68%;
}
table.details tr th{
    font-weight: bold;
    text-align:center;
    background:#a6caf0;
}
table.details tr td{
    background:#eeeee0;
}
table.general tr th{
    font-weight: bold;
    text-align:center;
    background:#a6caf0;
}
table.general tr td{
    background:#eeeee0;
}
h1 {
    margin: 0px 0px 5px; font: 250% verdana,arial,helvetica; text-align:center;
}
h2 {
    margin-top: 1em; margin-bottom: 0.5em; font: bold 125% verdana,arial,helvetica; text-align:center;
}
.fail {
    font-weight:bold; color:purple;
}
</style>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>SDET Test Report </title>
</head>
<body>
<h1>SDET Test Report For </h1><h2>"""
html2 = """</h2>
<h1>Download or Flash Failed!</h1>
<table class="general" border="1" cellpadding="7" cellspacing="0" width="70%" align="center">
<tr><th class=fail>失败的具体可能原因：</th></tr>
<tr><td class=details>"""
html3="""</td></tr>
<table>
</body>
</html>"""

def cur_file_dir():
     #获取脚本路径
     path = sys.path[0]
     #判断为脚本文件还是py2exe编译后的文件，如果是脚本文件，则返回的是脚本的目录，如果是py2exe编译后的文件，则返回的是编译后的文件路径
     if os.path.isdir(path):
         return path
     elif os.path.isfile(path):
         return os.path.dirname(path)

if __name__ == '__main__':
    productName = os.getenv('PRODUCT_NAME')
    currentTest = os.getenv('CURRENT_TEST')
    mailRecipients = os.getenv('REPORT_RECIPIENTS')
    try:
        failReason = open(os.path.join(currentTest, "fail.txt")).read()
    except Exception, e:
        failReason = currentTest+" Failed"
    
    html = html1 + productName + html2 + cgi.escape(failReason, True) + html3
    f = open("fail.html", "w")
    f.write(html)
    f.close()
    mailTo = ""
    mailCC = ""
    for line in mailRecipients.split("\n"):
        a,b = line.split(":")
        if a.strip().upper() == "TO":
            mailTo = b.strip()
        if a.strip().upper() == "CC":
            mailCC = b.strip()
    print "Mailcc: ", mailCC
    print "MailTo: ", mailTo
    currentTime=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time()))
    subject = "【"+productName +"】"+currentTime+"构建版本测试报告——" + currentTest+" Failed"
    upload = UploadFileByHttp(productName, "", subject, mailTo, mailCC, "fail.html")
    upload.uploadfile()
    print upload.get_upload_result()
